package com.dingxin.ship_together_api.service.impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dingxin.ship_together_api.common.utils.AesCbcUtil;
import com.dingxin.ship_together_api.config.exception.CustomException;
import com.dingxin.ship_together_api.entity.SysUser;
import com.dingxin.ship_together_api.entity.SysUserRole;
import com.dingxin.ship_together_api.entity.enums.ExceptionEnum;
import com.dingxin.ship_together_api.entity.enums.RoleEnum;
import com.dingxin.ship_together_api.mapper.SysUserMapper;
import com.dingxin.ship_together_api.mapper.SysUserRoleMapper;
import com.dingxin.ship_together_api.service.SysUserService;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
* Author: ctj
* Date: 2022-08-09
* Time: 10:55
*/

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService{

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Value("${appid}")
    private String appid;
    @Value("${secret}")
    private String secret;

    TimedCache<String, String> cache = CacheUtil.newTimedCache(10 * 1000);


    @Override public boolean checkVerifyCode(String verifyCode, HttpServletRequest request) {
        if (!CaptchaUtil.ver(verifyCode, request)) {
            CaptchaUtil.clear(request);  // 验证码校验失败,清除session中的验证码
            return false;
        }
        return true;
    }

    @Override public String getOpenIdByCode(String code) {
        String s = HttpUtil.get(
            "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&appid=" +
                appid+
                "&secret="+
                secret+
                "&js_code="+
                code);
        Map<String, Object> map = JSON.parseObject(s, Map.class);
        if (map.get("openid") == null) {
            throw new CustomException(ExceptionEnum.MISSING_PARAMETER);
        } else {
            cache.put("openId", (String)map.get("openid"));
            cache.put("sessionKey", (String)map.get("session_key"));
            return (String)map.get("openid");
        }
    }

    @Override public Map<String,String> login(String encryptedData, String iv, String code) {
        // 获取openId并登录
        String openId = getOpenIdByCode(code);
        // 解析手机号
        // Map<String, Object> map =
        //     DecryptWxPhone.getPhoneNumber(encryptedData, cache.get("sessionKey"), iv);
        Map<String, Object> map = null;
        try {
            map = AesCbcUtil.decrypt(encryptedData, cache.get("sessionKey"), iv, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String phone = (String)map.get("purePhoneNumber");
        // 查询phone 和openId 是否联合唯一，否则创建新用户插入到表里，再登录
        SysUser sysUser = sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq(SysUser.COL_PHONE_NUMBER, phone).eq(SysUser.COL_OPEN_ID, openId));
        if (sysUser == null) {
            // 创建新用户
            SysUser addUser = new SysUser();
            addUser.setPhoneNumber(Long.parseLong(phone));
            addUser.setOpenId(openId);
            sysUserMapper.insert(addUser);
            // 赋上角色
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(addUser.getId());
            userRole.setRoleId(RoleEnum.USER.getId());
            sysUserRoleMapper.insert(userRole);
            // 登录
            StpUtil.login(addUser.getId());
            SaSession session = StpUtil.getSession();
            session.set("user",addUser);
        }else {
            StpUtil.login(sysUser.getId());
            SaSession session = StpUtil.getSession();
            session.set("user",sysUser);
        }
        SaSession session = StpUtil.getSession();
        session.set("openId",openId);
        session.set("sessionKey",cache.get("sessionKey"));
        session.set("phone",phone);
        // 组装返回数据
        HashMap<String, String> resMap = new HashMap<>();
        resMap.put("phone",phone);
        resMap.put("openId",openId);
        resMap.put("token",StpUtil.getTokenValue());
        return resMap;
    }


}
